{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:13:24.891350Z",
     "start_time": "2019-02-26T08:13:24.737438Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3.4.1'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import cv2\n",
    "cv2.__version__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 更改色彩空间\n",
    "学习目标：\n",
    "- 改变色彩空间 $BGR \\leftrightarrow Gray, BGR \\leftrightarrow HSV$ 等。\n",
    "- 创建一个应用程序来提取视频中的彩色对象\n",
    "- cv2.cvtColor(), cv2.inRange() "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 改变色彩空间\n",
    "OpenCV 中有 150 多种色彩空间转化的方法，这里只讨论两种：$BGR \\leftrightarrow Gray, BGR \\leftrightarrow HSV$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:13:27.586807Z",
     "start_time": "2019-02-26T08:13:27.582810Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:13:28.598227Z",
     "start_time": "2019-02-26T08:13:28.583237Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# OpenCV 中色彩空间的方法\n",
    "flags = [i for i in dir(cv2) if i.startswith('COLOR_')]\n",
    "flags"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "['COLOR_BAYER_BG2BGR',\n",
    " 'COLOR_BAYER_BG2BGRA',\n",
    " 'COLOR_BAYER_BG2BGR_EA',\n",
    " 'COLOR_BAYER_BG2BGR_VNG',\n",
    " 'COLOR_BAYER_BG2GRAY',\n",
    " 'COLOR_BAYER_BG2RGB',\n",
    " 'COLOR_BAYER_BG2RGBA',\n",
    " 'COLOR_BAYER_BG2RGB_EA',\n",
    " 'COLOR_BAYER_BG2RGB_VNG',\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "HSV的色相范围为[0,179]，饱和度范围为[0,255]，值范围为[0,255]。不同的软件使用不同的规模。如果要比较 OpenCV 值和它们，你需要标准化这些范围。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 目标跟踪"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "HSV 和 HLV 解释\n",
    "![](https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Hsl-hsv_models.svg/400px-Hsl-hsv_models.svg.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:13:41.115060Z",
     "start_time": "2019-02-26T08:13:31.977295Z"
    }
   },
   "outputs": [],
   "source": [
    "cap = cv2.VideoCapture(0)\n",
    "\n",
    "while(1):\n",
    "    # 提取每一帧, frame 源视频\n",
    "    _, frame = cap.read()\n",
    "\n",
    "    # BGR -> HSV\n",
    "    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n",
    "\n",
    "    # 在 HSV 中定义蓝色的范围\n",
    "    lower_blue = np.array([110, 50, 50], dtype=np.uint8)\n",
    "    upper_blue = np.array([130, 255, 255], dtype=np.uint8)\n",
    "\n",
    "    # 将 HSV 图像的阈值设置为只获取蓝色\n",
    "    mask = cv2.inRange(hsv, lower_blue, upper_blue) \n",
    "    # 把像素值在 lower_blue 和 upper_blue 之间的像素置 255(白)，之外的置 0（黑）\n",
    "\n",
    "    #\n",
    "    res = cv2.bitwise_and(frame, frame, mask=mask) # 白留黑除\n",
    "\n",
    "    cv2.imshow(\"frame\", frame) # 源视频\n",
    "    cv2.imshow(\"hsv\", hsv) # \n",
    "    cv2.imshow(\"mask\", mask)\n",
    "    cv2.imshow(\"res\", res)\n",
    "    k = cv2.waitKey(1) & 0xFF\n",
    "    if k == 27:\n",
    "        break\n",
    "\n",
    "cap.release() # 记得释放掉捕获的视频\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-01T11:57:31.083331Z",
     "start_time": "2019-02-01T11:57:31.072336Z"
    }
   },
   "source": [
    "运行结果：该段程序的作用是检测蓝色目标，同理可以检测其他颜色的目标\n",
    "**结果中存在一定的噪音，之后的章节将会去掉它**\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzr6e2twz4j211y0lcn9t.jpg)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-11T11:58:29.378916Z",
     "start_time": "2019-03-11T11:58:14.576365Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "def hsv_trace(img):\n",
    "    \"\"\"\n",
    "    颜色跟踪，img 三通道图像\n",
    "    \"\"\"\n",
    "    # BGR -> HSV\n",
    "    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n",
    "\n",
    "    # 在 HSV 中定义蓝色的范围\n",
    "    lower_blue = np.array([100, 43, 46], dtype=np.uint8)\n",
    "    upper_blue = np.array([124, 255, 255], dtype=np.uint8)\n",
    "\n",
    "    # 将 HSV 图像的阈值设置为只获取蓝色\n",
    "    mask = cv2.inRange(hsv, lower_blue, upper_blue) \n",
    "    # 把像素值在 lower_blue 和 upper_blue 之间的像素置 255(白)，之外的置 0（黑）\n",
    "\n",
    "    res = cv2.bitwise_and(img, img, mask=mask) # 白留黑除\n",
    "    #cv2.imshow(\"hsv\", hsv) # \n",
    "    #cv2.imshow(\"mask\", mask)\n",
    "    cv2.imshow(\"res\", res)\n",
    "    \n",
    "    \n",
    "img = cv2.imread(\"./sample_img/car_num_2.jpg\")\n",
    "hsv_trace(img)\n",
    "\n",
    "cv2.imshow(\"img\", img) # 源视频\n",
    "\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这是物体跟踪中最简单的方法。一旦你学会了等高线的函数，你可以做很多事情，比如找到这个物体的质心，用它来跟踪这个物体，仅仅通过在相机前移动你的手来画图表，还有很多其他有趣的事情。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 如何找到要跟踪的 HSV 值?\n",
    "[菜鸟教程 在线 HSV-> BGR 转换] (https://c.runoob.com/front-end/868)\n",
    "\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0z3dvyykij20ap092410.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:13:47.338497Z",
     "start_time": "2019-02-26T08:13:47.332503Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[120, 255, 255]]], dtype=uint8)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "green = np.uint8([[[255, 0, 0]]])\n",
    "hsv_green = cv2.cvtColor(green, cv2.COLOR_BGR2HSV)\n",
    "hsv_green"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "比如要找出绿色的 HSV 值，可以使用上面的程序，得到的值取一个上下界。如上面的取下界 [H-10, 100, 100]，上界 [H+10, 255, 255]\n",
    "或者使用其他工具如 [GIMP] (https://www.gimp.org/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 更多例程（跟踪红色目标和绿色目标）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 红色目标"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-12T11:56:51.115442Z",
     "start_time": "2019-03-12T11:56:12.420520Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "cap = cv2.VideoCapture(0)\n",
    "\n",
    "while(1):\n",
    "    # 提取每一帧, frame 源视频\n",
    "    _, frame = cap.read()\n",
    "\n",
    "    # BGR -> HSV\n",
    "    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n",
    "\n",
    "    # 在 HSV 中定义蓝色的范围\n",
    "    lower_blue = np.array([35, 43, 46], dtype=np.uint8)\n",
    "    upper_blue = np.array([77, 255, 255], dtype=np.uint8)\n",
    "\n",
    "    # 将 HSV 图像的阈值设置为只获取蓝色\n",
    "    mask = cv2.inRange(hsv, lower_blue, upper_blue) \n",
    "    # 把像素值在 lower_blue 和 upper_blue 之间的像素置 255(白)，之外的置 0（黑）\n",
    "\n",
    "    #\n",
    "    res = cv2.bitwise_and(frame, frame, mask=mask) # 白留黑除\n",
    "\n",
    "    cv2.imshow(\"frame\", frame) # 源视频\n",
    "    cv2.imshow(\"hsv\", hsv) # \n",
    "    cv2.imshow(\"mask\", mask)\n",
    "    cv2.imshow(\"res\", res)\n",
    "    k = cv2.waitKey(1) & 0xFF\n",
    "    if k == 27:\n",
    "        break\n",
    "\n",
    "cap.release() # 记得释放掉捕获的视频\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 绿色目标"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "cap = cv2.VideoCapture(0)\n",
    "\n",
    "while(1):\n",
    "    # 提取每一帧, frame 源视频\n",
    "    _, frame = cap.read()\n",
    "\n",
    "    # BGR -> HSV\n",
    "    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n",
    "\n",
    "    # 在 HSV 中定义蓝色的范围\n",
    "    lower_blue = np.array([0, 43, 46], dtype=np.uint8)\n",
    "    upper_blue = np.array([10, 255, 255], dtype=np.uint8)\n",
    "\n",
    "    # 将 HSV 图像的阈值设置为只获取蓝色\n",
    "    mask = cv2.inRange(hsv, lower_blue, upper_blue) \n",
    "    # 把像素值在 lower_blue 和 upper_blue 之间的像素置 255(白)，之外的置 0（黑）\n",
    "\n",
    "    #\n",
    "    res = cv2.bitwise_and(frame, frame, mask=mask) # 白留黑除\n",
    "\n",
    "    cv2.imshow(\"frame\", frame) # 源视频\n",
    "    cv2.imshow(\"hsv\", hsv) # \n",
    "    cv2.imshow(\"mask\", mask)\n",
    "    cv2.imshow(\"res\", res)\n",
    "    k = cv2.waitKey(1) & 0xFF\n",
    "    if k == 27:\n",
    "        break\n",
    "\n",
    "cap.release() # 记得释放掉捕获的视频\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-01T13:51:51.854Z"
    }
   },
   "source": [
    "### 图像阈值\n",
    "学习目标：\n",
    "- 简单阈值处理、自适应阈值处理、 Otsu's 阈值处理\n",
    "- cv2.threshold, cv2.adaptiveThreshold\n",
    "\n",
    "对图像进行阈值处理，算是一种最简单的图像分割方法，基于图像与背景之间的灰度差异，此项分割是基于像素级的分割"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 简单阈值处理\n",
    "threshold(src, thresh, maxval, type[, dst]) -> retval, dst\n",
    "- src: 源图像，必须是灰度图\n",
    "- thresh：阈值，用于对像素的区分\n",
    "- maxval: 当像素大于等于阈值时，将像素赋值为 maxval\n",
    "- 阈值样式：\n",
    "```python\n",
    "cv2.THRESH_BINARY # 若源像素大于阈值，设置为 maxval，否则设置为 0\n",
    "cv2.THRESH_BINARY_INV # 与上面相反，若源像素大于阈值，则将像素设置为 0，否则是设置为 maxval\n",
    "cv2.THRESH_TRUNC # 若源像素大于阈值，设定为阈值, maxval 被忽略 否则像素保持不变\n",
    "cv2.THRESH_TOZERO # 若源像素大于阈值，保持像素不变，否则设置为 0， maxval 被忽略\n",
    "cv2.THRESH_TOZERO_INV # 与上面相反，若源像素大于阈值，设置为 0，否则保持像素不变， maxval 被忽略\n",
    "```\n",
    "- retval: 下面介绍\n",
    "- dst: 得到的图像\n",
    "\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzs9quix4pj20ez0dpacm.jpg)\n",
    "\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzs9s01sd6j20fz0f977y.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T13:36:31.127730Z",
     "start_time": "2019-03-10T13:36:30.589044Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "img = cv2.imread(\"./sample_img/gradient.png\", 0)\n",
    "ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)\n",
    "ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)\n",
    "ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)\n",
    "ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)\n",
    "ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)\n",
    "\n",
    "titles = ['Original Image', 'BINARY',\n",
    "          'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']\n",
    "images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]\n",
    "\n",
    "for i in range(6):\n",
    "    plt.subplot(2, 3, i+1), plt.imshow(images[i], 'gray')\n",
    "    plt.title(titles[i])\n",
    "    plt.xticks([]), plt.yticks([])\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0jw7kco9gj209a068glt.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 自适应阈值处理\n",
    "计算图像小区域的阈值。所以我们对同一幅图像的不同区域得到不同的阈值，这给我们在不同光照下的图像提供了更好的结果。\n",
    "\n",
    "三个特殊的输入参数和一个输出参数\n",
    "\n",
    "`adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) -> dst`\n",
    "- Adaptive Method：\n",
    "```python\n",
    "cv2.ADAPTIVE_THRESH_MEAN_C # 阈值是临近区域的平均值\n",
    "cv2.ADAPTIVE_THRESH_GAUSSIAN_C # 阈值是权值为高斯窗口的邻域值的加权和。\n",
    "```\n",
    "- thresholdType \n",
    "```python\n",
    "THRESH_BINARY # 若源像素大于阈值，则像素赋值 maxval，否则为 0\n",
    "THRESH_BINARY_INV # 与上面相反\n",
    "```\n",
    "- Block Size：\n",
    "决定临近区域的大小，$BlockSize*BlockSize$，取3，5，7等（取奇数）\n",
    "- C：\n",
    "从计算的平均值或加权平均值中减去的一个常数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:14:31.470227Z",
     "start_time": "2019-02-26T08:14:30.660688Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "img = cv2.imread('./sample_img/dave.png', 0)\n",
    "img = cv2.medianBlur(img, 5)\n",
    "\n",
    "ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)\n",
    "# 若源像素大于阈值（阈值为临近区域的平均值减去常数），设置为 maxval， 否则置 0\n",
    "th2 = cv2.adaptiveThreshold(\n",
    "    img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 4)\n",
    "th3 = cv2.adaptiveThreshold(\n",
    "    img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 3, 4)\n",
    "\n",
    "titles = ['Original Image', 'Global Thresholding (v = 127)',\n",
    "          'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']\n",
    "images = [img, th1, th2, th3]\n",
    "\"\"\"\n",
    "cv2.imshow(\"th1\", th1)\n",
    "cv2.imshow(\"th2\", th2)\n",
    "cv2.imshow(\"th3\", th3)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()\n",
    "\"\"\"\n",
    "for i in range(4):\n",
    "    plt.subplot(2, 2, i+1)\n",
    "    plt.imshow(images[i], 'gray')\n",
    "    plt.title(titles[i])\n",
    "    plt.xticks([]), plt.yticks([])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0jw822a5pj209r06fwf2.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Otsu’s 二值化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:14:54.544012Z",
     "start_time": "2019-02-26T08:14:51.694649Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "img = cv2.imread(\"./sample_img/noisy2.png\", 0)\n",
    "\n",
    "# global thresholding\n",
    "ret1, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)\n",
    "\n",
    "# Otsu's thresholding\n",
    "ret2, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n",
    "\n",
    "# Otsu's thresholding after Gaussian filtering\n",
    "blur = cv2.GaussianBlur(img, (5, 5), 0)\n",
    "ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n",
    "\n",
    "# plot all the images and their histograms\n",
    "images = [img, 0, th1,\n",
    "          img, 0, th2,\n",
    "          blur, 0, th3]\n",
    "titles = ['Original Noisy Image', 'Histogram', 'Global Thresholding (v=127)',\n",
    "          'Original Noisy Image', 'Histogram', \"Otsu's Thresholding\",\n",
    "          'Gaussian filtered Image', 'Histogram', \"Otsu's Thresholding\"]\n",
    "\n",
    "for i in range(3):\n",
    "    plt.subplot(3, 3, i*3+1), plt.imshow(images[i*3], 'gray')\n",
    "    plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])\n",
    "    plt.subplot(3, 3, i*3+2), plt.hist(images[i*3].ravel(), 256)\n",
    "    plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])\n",
    "    plt.subplot(3, 3, i*3+3), plt.imshow(images[i*3+2], 'gray')\n",
    "    plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0jw8d0fz8j20b006bmxn.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 原理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-13T01:36:10.131208Z",
     "start_time": "2019-03-13T01:36:04.472437Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "\n",
    "def OTSU_enhance(img_gray, th_begin=0, th_end=256, th_step=1):\n",
    "\n",
    "    max_g = 0\n",
    "    suitable_th = 0\n",
    "    for threshold in range(th_begin, th_end, th_step):\n",
    "        bin_img = img_gray > threshold\n",
    "        bin_img_inv = img_gray <= threshold\n",
    "        fore_pix = np.sum(bin_img)\n",
    "        back_pix = np.sum(bin_img_inv)\n",
    "        if 0 == fore_pix:\n",
    "            break\n",
    "        if 0 == back_pix:\n",
    "            continue\n",
    "\n",
    "        w0 = float(fore_pix) / img_gray.size  # 前景像素点占整幅图像大小的比例\n",
    "        u0 = float(np.sum(img_gray * bin_img)) / fore_pix  # 前景像素点的平均值\n",
    "        w1 = float(back_pix) / img_gray.size  # 背景像素点占整幅图像大小的比例\n",
    "        u1 = float(np.sum(img_gray * bin_img_inv)) / back_pix  # 前景像素点的平均值\n",
    "        # intra-class variance\n",
    "        g = w0 * w1 * (u0 - u1) * (u0 - u1)\n",
    "        if g > max_g:\n",
    "            max_g = g\n",
    "            suitable_th = threshold\n",
    "    return suitable_th\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/1.jpg\", 0)\n",
    "threshold = OTSU_enhance(gray)\n",
    "ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)\n",
    "_, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_OTSU)\n",
    "cv2.imshow(\"thresh1\", thresh1)\n",
    "cv2.imshow(\"thresh2\", thresh2)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-13T01:37:44.265834Z",
     "start_time": "2019-03-13T01:37:44.245847Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ True,  True,  True, ...,  True,  True,  True],\n",
       "       [ True,  True,  True, ...,  True,  True,  True],\n",
       "       [ True,  True,  True, ...,  True,  True,  True],\n",
       "       ...,\n",
       "       [ True,  True,  True, ...,  True,  True,  True],\n",
       "       [ True,  True,  True, ...,  True,  True,  True],\n",
       "       [ True,  True,  True, ...,  True,  True,  True]])"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "img_gray = cv2.imread(\"./sample_img/1.jpg\", 0)\n",
    "bin_img = img_gray > 0\n",
    "img*bin_img"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 更多资料\n",
    "[opencv-threshold-python] (https://www.learnopencv.com/opencv-threshold-python-cpp/)\n",
    "\n",
    "[OpenCV 图片集] (https://github.com/opencv/opencv/tree/master/samples/data)\n",
    "\n",
    "[本节原文] (https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html#thresholding)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 图像的几何变换\n",
    "学习目标：\n",
    "- 学习将不同的几何变换应用于图像，如平移、旋转、仿射变换等。\n",
    "- cv2.getPerspectiveTransform"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 变换\n",
    "OpenCV 提供两种变换函数：`cv2.warpAffine` 和 `cv2.warpPerspective`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 缩放\n",
    "`cv2.resize()` 完成缩放\n",
    "- src: 输入的图像\n",
    "- dsize: 输出图像的大小，设置为 None 则由 fx, fy 决定\n",
    "- fx: 宽度的缩放比例\n",
    "- fy: 高度的缩放比例\n",
    "- interpolation：插值方法\n",
    "    - INTER_NEAREST - 最近邻插值 (速度最快)\n",
    "    - INTER_LINEAR - 双线性插值（默认） **放大的效果还 OK ，速度较快**\n",
    "    - INTER_AREA - 使用像素区域关系重新采样。它可能是图像抽取的首选方法，因为它可以提供无莫尔条纹的结果。但是当图像被缩放时，它类似于 INTER_NEAREST 方法。 **缩小图像效果最好的方法**\n",
    "    - INTER_CUBIC - 4x4 像素邻域上的双三次插值 **放大的效果最好（慢）**\n",
    "    - INTER_LANCZOS4 - 8x8 像素邻域的 Lanczos 插值\n",
    "- dst: 输出图像\n",
    "\n",
    "[文档说明] (https://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html?highlight=resize#resize)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:15:16.189620Z",
     "start_time": "2019-02-26T08:15:15.080255Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "def opencv2matplot(src):\n",
    "    \"\"\"\n",
    "    将 opencv 颜色通道转换成 matplot 的颜色通道\n",
    "    \"\"\"\n",
    "    b, g, r = cv2.split(src)\n",
    "    return cv2.merge([r, g, b])\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/messi5.jpg\")\n",
    "# 方法一\n",
    "res = cv2.resize(img, None, fx=2, fy=3, interpolation=cv2.INTER_CUBIC)\n",
    "# 方法二\n",
    "height, width = img.shape[:2]\n",
    "res_2 = cv2.resize(img, (2*width, 2*height), interpolation=cv2.INTER_CUBIC)\n",
    "\n",
    "images = [img, res, res_2]\n",
    "img_title = ['Original', \"method_1\", \"method_2\"]\n",
    "for i, img in enumerate(images):\n",
    "    plt.subplot(1, 3, i+1)\n",
    "    plt.imshow(opencv2matplot(img))\n",
    "    plt.title(img_title[i])\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运行结果\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzsbyblerbj20bh03zabj.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:16:39.445942Z",
     "start_time": "2019-02-26T08:15:20.646086Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "13.5 ms ± 680 µs per loop (mean ± std. dev. of 10 runs, 100 loops each)\n",
      "17.2 ms ± 2.2 ms per loop (mean ± std. dev. of 10 runs, 100 loops each)\n",
      "12.1 ms ± 1.85 ms per loop (mean ± std. dev. of 10 runs, 100 loops each)\n",
      "20.5 ms ± 7 ms per loop (mean ± std. dev. of 10 runs, 100 loops each)\n",
      "79.3 ms ± 2.19 ms per loop (mean ± std. dev. of 10 runs, 10 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit -r 10 res = cv2.resize(img, None, fx=2, fy=3, interpolation=cv2.INTER_CUBIC)\n",
    "%timeit -r 10 res = cv2.resize(img, None, fx=2, fy=3, interpolation=cv2.INTER_LINEAR)\n",
    "%timeit -r 10 res = cv2.resize(img, None, fx=2, fy=3, interpolation=cv2.INTER_NEAREST)\n",
    "%timeit -r 10 res = cv2.resize(img, None, fx=2, fy=3, interpolation=cv2.INTER_AREA)\n",
    "%timeit -r 10 res = cv2.resize(img, None, fx=2, fy=3, interpolation=cv2.INTER_LANCZOS4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**说明** : `cv2.INTER_LINEAR` 方法比 `cv2.INTER_CUBIC` 还慢，好像与官方文档说的不一致？ 有待验证。\n",
    "\n",
    "速度比较： INTER_CUBIC > INTER_NEAREST > INTER_LINEAR > INTER_AREA > INTER_LANCZOS4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 平移\n",
    "改变图像的位置，创建一个 `np.float32` 类型的变换矩阵，\n",
    "\n",
    "$M = \\begin{bmatrix} 1 & 0 & t_x \\\\ 0 & 1 & t_y \\end{bmatrix}$\n",
    "\n",
    "`warpAffine(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) -> dst`\n",
    "- src: 源图像\n",
    "- M：变换矩阵。 $t_x$（列偏移） $t_y$（行偏移） 就是要偏移的量\n",
    "- dsize: 输出图像的大小，形式如： (width, height)。width：列数， height：行数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:16:49.645104Z",
     "start_time": "2019-02-26T08:16:48.266896Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "img = cv2.imread('messi5.jpg', 0)\n",
    "rows,cols = img.shape \n",
    "\n",
    "M = np.float32([[1,0,100],[0,1,50]])\n",
    "dst = cv2.warpAffine(img, M, (cols,rows))\n",
    "\n",
    "cv2.imshow('img',dst)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运行结果：\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzsidqwe12j20fp0amq6b.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-02T15:02:25.449803Z",
     "start_time": "2019-02-02T15:02:25.405827Z"
    }
   },
   "source": [
    "##### 旋转\n",
    "旋转角度（$\\theta$）是通过一个变换矩阵变换的：\n",
    "$M = \\begin{bmatrix}\\cos\\theta & -\\sin\\theta \\\\ \\sin\\theta & \\cos\\theta \\end{bmatrix}$\n",
    " \n",
    "OpenCV 提供的是可调旋转中心的缩放旋转，这样你可以在任何你喜欢的位置旋转。修正后的变换矩阵为\n",
    "$\\begin{bmatrix} \\alpha &  \\beta & (1- \\alpha )  \\cdot center.x -  \\beta \\cdot center.y \\\\ - \\beta &  \\alpha &  \\beta \\cdot center.x + (1- \\alpha )  \\cdot center.y \\end{bmatrix}$\n",
    "\n",
    "这里 \n",
    "$\\begin{array}{l} \\alpha =  scale \\cdot \\cos \\theta , \\\\ \\beta =  scale \\cdot \\sin \\theta \\end{array}$\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "OpenCV 提供了 `cv2.getRotationMatrix2D` 控制\n",
    "cv2.getRotationMatrix2D(center, angle, scale) → retval\n",
    "- center: 源图像的旋转中心\n",
    "- angle: 角度的旋转。正值表示逆时针旋转(假设坐标原点为左上角)。\n",
    "- scale: 比例因子"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:16:53.139103Z",
     "start_time": "2019-02-26T08:16:51.912808Z"
    }
   },
   "outputs": [],
   "source": [
    "img = cv2.imread(\"messi5.jpg\", 0)\n",
    "rows, cols = img.shape\n",
    "\n",
    "M = cv2.getRotationMatrix2D((cols/2, rows/2), 90, 0.9)\n",
    "# 设置旋转中心为源图像的图中心，逆时针旋转 90 度，缩放比例为 0.9\n",
    "\n",
    "dst = cv2.warpAffine(img, M, (cols, rows))\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"dst\", dst)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-02T15:16:37.957424Z",
     "start_time": "2019-02-02T15:16:37.950423Z"
    }
   },
   "source": [
    "运行结果\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzshleydevj20ut0afgtv.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 仿射变换"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "cv2.getAffineTransform(src, dst) → retval\n",
    "- src: 源图像中三角形顶点的坐标。\n",
    "- dst: 目标图像中相应三角形顶点的坐标。\n",
    "- retval: 得到一个矩阵 map_matrix\n",
    "\n",
    "函数关系：\n",
    "$\\begin{bmatrix} x'_i \\\\ y'_i \\end{bmatrix}$ = $\\texttt {map_matrix} \\cdot \\begin{bmatrix} x_i \\\\ y_i \\\\ 1 \\end{bmatrix}$\n",
    "\n",
    "其中\n",
    "$dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### 例程 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:16:57.478620Z",
     "start_time": "2019-02-26T08:16:55.893529Z"
    }
   },
   "outputs": [],
   "source": [
    "# 创建一个测试图片，便于观察\n",
    "img = np.zeros((512, 512, 3), dtype=np.uint8) + 255\n",
    "cv2.circle(img, (50, 50), 7, (255, 0, 0), -1)\n",
    "cv2.circle(img, (200, 50), 7, (255, 0, 0), -1)\n",
    "cv2.circle(img, (50, 200), 7, (255, 0, 0), -1)\n",
    "cv2.imwrite(\"./sample_img/drawing_2.png\", img)\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:17:00.113110Z",
     "start_time": "2019-02-26T08:16:58.135242Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%matplotlib notebook\n",
    "def opencv2matplot(src):\n",
    "    \"\"\"\n",
    "    将 opencv 颜色通道转换成 matplot 的颜色通道\n",
    "    \"\"\"\n",
    "    b, g, r = cv2.split(src)\n",
    "    return cv2.merge([r, g, b])\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/drawing_2.png\")\n",
    "#img = cv2.resize(img, None, fx=0.2, fy=0.2, interpolation=cv2.INTER_NEAREST) # 源图片太大了，进行缩放\n",
    "rows, cols, ch = img.shape\n",
    "\n",
    "pts1 = np.float32([[50, 50], [200, 50], [50, 200]])\n",
    "pts2 = np.float32([[10, 100], [200, 50], [100, 250]])\n",
    "\n",
    "M = cv2.getAffineTransform(pts1, pts2)\n",
    "\n",
    "dst = cv2.warpAffine(img, M, (cols, rows))\n",
    "\n",
    "plt.subplot(1, 2, 1)\n",
    "plt.imshow(img)\n",
    "\n",
    "plt.subplot(1, 2, 2)\n",
    "plt.imshow(dst)\n",
    "plt.show()\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"dst\", dst)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运行结果：图上的点便于观察，两图中的红点是相互对应的\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzsjr8k543j20jn09gwel.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### 平移"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:17:21.482872Z",
     "start_time": "2019-02-26T08:17:21.432906Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "def opencv2matplot(src):\n",
    "    \"\"\"\n",
    "    将 opencv 颜色通道转换成 matplot 的颜色通道\n",
    "    \"\"\"\n",
    "    b, g, r = cv2.split(src)\n",
    "    return cv2.merge([r, g, b])\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/drawing_2.png\")\n",
    "#img = cv2.resize(img, None, fx=0.2, fy=0.2, interpolation=cv2.INTER_NEAREST) # 源图片太大了，进行缩放\n",
    "rows, cols, ch = img.shape\n",
    "\n",
    "pts1 = np.float32([[50, 50], [200, 50], [50, 200]])\n",
    "pts2 = np.float32([[100, 100], [250, 100], [100, 250]])\n",
    "\n",
    "M = cv2.getAffineTransform(pts1, pts2)\n",
    "\n",
    "dst = cv2.warpAffine(img, M, (cols, rows))\n",
    "\n",
    "plt.subplot(1, 2, 1)\n",
    "plt.imshow(img)\n",
    "\n",
    "plt.subplot(1, 2, 2)\n",
    "plt.imshow(dst)\n",
    "plt.show()\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 透视转换\n",
    "透视变换需要一个 3x3 变换矩阵。转换之后直线仍然保持笔直，要找到这个变换矩阵，需要输入图像上的 4 个点和输出图像上的对应点。在这 4 个点中，有 3 个不应该共线。通过 `cv2.getPerspectiveTransform` 计算得到变换矩阵，得到的矩阵 `cv2.warpPerspective` 变换得到最终结果。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:17:39.823886Z",
     "start_time": "2019-02-26T08:17:38.333739Z"
    }
   },
   "outputs": [],
   "source": [
    "img = cv2.imread(\"./sample_img/sudokusmall.png\")\n",
    "rows, cols, ch = img.shape\n",
    "\n",
    "pts1 = np.float32([[73, 85], [488, 71], [36, 513], [518, 518]])\n",
    "pts2 = np.float32([[0, 0], [350, 0], [0, 350], [350, 350]])\n",
    "\n",
    "M = cv2.getPerspectiveTransform(pts1, pts2)                \n",
    "\n",
    "dst = cv2.warpPerspective(img, M, (350, 350))\n",
    "cv2.imwrite(\"dst.png\", dst)\n",
    "plt.subplot(121),plt.imshow(img),plt.title('Input')\n",
    "plt.subplot(122),plt.imshow(dst),plt.title('Output')\n",
    "plt.show()\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"dst\", dst)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fztoyo59vuj20ph0g8tlx.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 更多资料\n",
    "[本节原文] (https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.html)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 线性滤波：方框滤波、均值滤波、高斯滤波"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 平滑处理\n",
    "平滑处理（smoothing）也称模糊处理（bluring）,是一种简单且使用频率很高的图像处理方法。平滑处理的用途：常见是用来**减少图像上的噪点或失真**。在涉及到降低图像分辨率时，平滑处理是很好用的方法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 图像滤波与滤波器\n",
    "图像滤波：尽量保留图像细节特征的条件下对目标图像的噪声进行抑制，其处理效果的好坏将直接影响到后续图像处理和分析的有效性和可靠性。\n",
    "\n",
    "消除图像中的噪声成分叫做图像的平滑化或滤波操作。信号或图像的能量大部分集中在幅度谱的低频和中频段，在高频段，有用的信息会被噪声淹没。因此一个能降低高频成分幅度的滤波器就能够减弱噪声的影响。\n",
    "\n",
    "滤波的目的：抽出对象的特征作为图像识别的特征模式；为适应图像处理的要求，消除图像数字化时混入的噪声。\n",
    "\n",
    "滤波处理的要求：不能损坏图像的轮廓及边缘等重要信息；图像清晰视觉效果好。\n",
    "\n",
    "平滑滤波是低频增强的空间滤波技术，目的：模糊和消除噪音。\n",
    "\n",
    "空间域的平滑滤波一般采用简单平均法，即求邻近像元点的平均亮度值。邻域的大小与平滑的效果直接相关，邻域越大平滑效果越好，但是邻域过大，平滑也会使边缘信息的损失的越大，从而使输出图像变得模糊。因此需要选择合适的邻域。\n",
    "\n",
    "滤波器：一个包含加权系数的窗口，利用滤波器平滑处理图像时，把这个窗口放在图像上，透过这个窗口来看我们得到的图像。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 线性滤波器\n",
    "线性滤波器：用于剔除输入信号中不想要的频率或者从许多频率中选择一个想要的频率。\n",
    "低通滤波器、高通滤波器、带通滤波器、带阻滤波器、全通滤波器、陷波滤波器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 常用滤波器\n",
    "##### 方框滤波器 (boxblur 函数)\n",
    "`boxFilter(src, ddepth, ksize[, dst[, anchor[, normalize[, borderType]]]]) -> dst`\n",
    "- src: 源图片\n",
    "- ddepth: 输出图像的深度， -1 代表使用原图深度\n",
    "- kesize: 核\n",
    "- dst: 输出图像\n",
    "- anchor：锚点，表示要处理的像素点 (-1, -1) 代表核的中心\n",
    "- normalize：表示内核是否被归一化，默认值: True **值为 True 时与 cv2.blur() 作用相同**。 ![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzyyr2xil7j20bu06k74v.jpg) \n",
    "- borderType：图像边缘处理参数\n",
    "\n",
    "均值滤波是方框滤波归一化后的特殊情况。归一化就是要把处理的量缩放到一个范围内如 (0,1)，以便统一处理和直观量化。非归一化的方框滤波用于计算每个像素邻近内的积分特性，比如密集光流算法中用到的图像倒数的协方差矩阵。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:17:45.692523Z",
     "start_time": "2019-02-26T08:17:44.389289Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "img = cv2.imread(\"./sample_img/opencv-logo.png\")\n",
    "\n",
    "boxFilter = cv2.boxFilter(img, -1, (5, 5), normalize=False) \n",
    "\n",
    "cv2.imshow(\"original\", img)\n",
    "cv2.imshow(\"boxFilter\", boxFilter)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运行结果：\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1fzyyzk0r8ij20y10lcmyf.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### 程序说明原理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:17:48.029186Z",
     "start_time": "2019-02-26T08:17:48.006198Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "temp:\n",
      "[[ 0  1  2  3  4]\n",
      " [ 5  6  7  8  9]\n",
      " [10 11 12 13 14]\n",
      " [15 16 17 18 19]\n",
      " [20 21 22 23 24]]\n",
      "result:\n",
      "[[ 36  39  48  57  60]\n",
      " [ 51  54  63  72  75]\n",
      " [ 96  99 108 117 120]\n",
      " [141 144 153 162 165]\n",
      " [156 159 168 177 180]]\n",
      "copyMakeBorder:\n",
      "[[ 6  5  6  7  8  9  8]\n",
      " [ 1  0  1  2  3  4  3]\n",
      " [ 6  5  6  7  8  9  8]\n",
      " [11 10 11 12 13 14 13]\n",
      " [16 15 16 17 18 19 18]\n",
      " [21 20 21 22 23 24 23]\n",
      " [16 15 16 17 18 19 18]]\n"
     ]
    }
   ],
   "source": [
    "# 构造一个例子进行说明\n",
    "temp = np.array([i for i in range(25)], dtype=np.uint8).reshape(5, 5)\n",
    "\n",
    "# cv2.BORDER_DEFAULT 是对边缘进行镜像操作\n",
    "result = cv2.boxFilter(temp, -1, (3, 3), normalize=False)\n",
    "print(\"temp:\", temp, \"result:\", result, \"copyMakeBorder:\", cv2.copyMakeBorder(temp, 1, 1, 1, 1, cv2.BORDER_DEFAULT), sep='\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 均值滤波（ blur 函数）\n",
    "\n",
    "均值滤波是典型的线性滤波算法，主要方法为邻域平均法，即用一片图像区域的各个像素的均值来代替原图像中的各个像素值。一般需要在图像上对目标像素给出一个模板（内核），该模板包括了其周围的临近像素（比如以目标像素为中心的周围8（3x3-1）个像素，构成一个滤波模板，即**去掉目标像素本身**）。再用模板中的全体像素的平均值来代替原来像素值。即对待处理的当前像素点（x，y），选择一个模板，该模板由其近邻的若干像素组成，求模板中所有像素的均值，再把该均值赋予当前像素点（x，y），作为处理后图像在该点上的灰度个g（x，y），即个g（x，y）=1/m ∑f（x，y） ，其中m为该模板中包含当前像素在内的像素总个数。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "均值滤波本身存在着固有的缺陷，即它不能很好地保护图像细节，在图像去噪的同时也破坏了图像的细节部分，从而使图像变得模糊，不能很好地去除噪声点。\n",
    "\n",
    "\n",
    "\n",
    "`cv2.blur(src, ksize[, dst[, anchor[, borderType]]]) → dst`\n",
    "- src：源图像\n",
    "- ksize：内核大小 （k, k） ![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzx2afnfn7j20e7034jr8.jpg)\n",
    "- anchor: 锚点 默认值点(- 1,1) 表示锚点位于内核中心。 \n",
    "- borderType：用于外推图像像素的边界模式。一般使用默认值即可。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:17:52.201796Z",
     "start_time": "2019-02-26T08:17:50.669693Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "img = cv2.imread(\"./sample_img/opencv-logo.png\")\n",
    "\n",
    "blur = cv2.blur(img, (5, 5)) \n",
    "\n",
    "cv2.imshow(\"original\", img)\n",
    "cv2.imshow(\"blur\", blur)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "结果：\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzx1teii11j20xe0lc407.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### 程序说明原理：图像边缘的处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:17:54.134691Z",
     "start_time": "2019-02-26T08:17:54.065728Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "temp:\n",
      "[[ 0  1  2  3  4]\n",
      " [ 5  6  7  8  9]\n",
      " [10 11 12 13 14]\n",
      " [15 16 17 18 19]\n",
      " [20 21 22 23 24]]\n",
      "result:\n",
      "[[ 4  4  5  6  7]\n",
      " [ 6  6  7  8  8]\n",
      " [11 11 12 13 13]\n",
      " [16 16 17 18 18]\n",
      " [17 18 19 20 20]]\n",
      "copyMakeBorder:\n",
      "[[ 6  5  6  7  8  9  8]\n",
      " [ 1  0  1  2  3  4  3]\n",
      " [ 6  5  6  7  8  9  8]\n",
      " [11 10 11 12 13 14 13]\n",
      " [16 15 16 17 18 19 18]\n",
      " [21 20 21 22 23 24 23]\n",
      " [16 15 16 17 18 19 18]]\n"
     ]
    }
   ],
   "source": [
    "# 构造一个例子进行说明\n",
    "temp = np.array([i for i in range(25)], dtype=np.uint8).reshape(5, 5)\n",
    "\n",
    "# cv2.BORDER_DEFAULT 是对边缘进行镜像操作\n",
    "result = cv2.blur(temp, (3, 3))\n",
    "print(\"temp:\", temp, \"result:\", result, \"copyMakeBorder:\", cv2.copyMakeBorder(temp, 1, 1, 1, 1, cv2.BORDER_DEFAULT), sep='\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 高斯滤波\n",
    "\n",
    "高斯滤波：线性滤波，可以消除高斯噪声，广泛应用于图像处理的减噪过程。高斯滤波就是对整幅图像进行加权平均的过程，每一个像素点的值，都由其本身和邻域内的其他像素值经过**加权平均**后得到。高斯滤波的具体操作是：用一个模板（或称卷积、掩模）扫描图像中的每一个像素，用模板确定的邻域内像素的加权平均灰度值去替代模板中心像素点的值。\n",
    "\n",
    "高斯滤波有用但是效率不高。\n",
    "\n",
    "高斯模糊技术生成的图像，其视觉效果就像是经过一个半透明屏幕在观察图像，这与镜头焦外成像效果散景以及普通照明阴影中的效果都明显不同。高斯平滑也用于计算机视觉算法中的预先处理阶段，以增强图像在不同比例大小下的图像效果（参见尺度空间表示以及尺度空间实现）。从数学的角度来看，图像的高斯模糊过程就是图像与正态分布做卷积。由于正态分布又叫作高斯分布，所以这项技术就叫作高斯模糊。\n",
    "\n",
    "高斯滤波器是一类根据高斯函数的形状来选择权值的线性平滑滤波器。**高斯平滑滤波器对于抑制服从正态分布的噪声非常有效。**\n",
    "\n",
    "一维零均值高斯函数为: $G(x) = \\exp (-x^2 / 2\\sigma^2)$ 高斯分布参数 $\\sigma$ 决定了高斯函数的宽度。\n",
    "\n",
    "对于图像处理来说，常用二维零均值离散高斯函数作平滑滤波器。二维高斯函数为： ![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzy358ep1hj208901idfn.jpg)\n",
    "\n",
    "\n",
    "高斯噪声的产生\n",
    "- 图像传感器在拍摄时视场不够明亮、亮度不够均匀；\n",
    "- 电路各元器件自身噪声和相互影响；\n",
    "- 图像传感器长期工作，温度过高。\n",
    "\n",
    "\n",
    "`GaussianBlur(src, ksize, sigmaX[, dst[, sigmaY[, borderType]]]) -> dst`\n",
    "- src: 源图片\n",
    "- ksize: 内核大小,。其中 ksize.width 和 ksize.height 可以不同，但他们都必须为正数和奇数。或者，它们可以是零的，它们都是由 sigma 计算而来。\n",
    "- sigmaX: 表示高斯核函数在 X 方向的的标准偏差。\n",
    "- dst：目标输出\n",
    "- sigmaY：表示高斯核函数在 Y 方向的的标准偏差。若 sigmaY 为零，就将它设为 sigmaX ，如果 sigmaX 和 sigmaY 都是 0，那么就由 ksize.width 和ksize.height 计算出来。\n",
    "- borderType: 边缘处理参数 \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:17:57.091995Z",
     "start_time": "2019-02-26T08:17:55.802736Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "img = cv2.imread(\"./sample_img/opencv-logo.png\")\n",
    "\n",
    "blur = cv2.GaussianBlur(img, (5, 5), 0) \n",
    "\n",
    "cv2.imshow(\"original\", img)\n",
    "cv2.imshow(\"blur\", blur)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzy2odujzfj20xm0lc40e.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 综合例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:18:00.277170Z",
     "start_time": "2019-02-26T08:17:58.686085Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "def nothing(x):\n",
    "    pass\n",
    "\n",
    "img_box = cv2.imread(\"./sample_img/opencv-logo.png\")\n",
    "img_blur = img_Gauusian = img_box\n",
    "cv2.namedWindow(\"image_boxFilter\")\n",
    "cv2.namedWindow(\"image_blur\")\n",
    "cv2.namedWindow(\"image_GaussianBlur\")\n",
    "\n",
    "cv2.createTrackbar(\"boxFilter\", \"image_boxFilter\", 1, 8, nothing)\n",
    "cv2.createTrackbar(\"blur\", \"image_blur\", 1, 8, nothing)\n",
    "cv2.createTrackbar(\"GaussianBlur\", \"image_GaussianBlur\", 1, 8, nothing)\n",
    "\n",
    "\n",
    "while(1):\n",
    "    box_val = cv2.getTrackbarPos(\"boxFilter\", \"image_boxFilter\")\n",
    "    blur_val = cv2.getTrackbarPos(\"blur\", \"image_blur\")\n",
    "    guassian_val = cv2.getTrackbarPos(\"GaussianBlur\", \"image_GaussianBlur\")\n",
    "    \n",
    "    \"\"\"     \n",
    "    if (box_val == 0) | (blur_val == 0) | (guassian_val == 0):\n",
    "        box_val = 1\n",
    "        blur_val = 1\n",
    "        guassian_val = 1\n",
    "    \"\"\"   \n",
    "    \n",
    "    img_box_dst = cv2.boxFilter(img_box, -1, (2*box_val+1, 2*box_val+1), normalize=False)\n",
    "    img_blur_dst = cv2.blur(img_blur, (2*blur_val+1, 2*blur_val+1))\n",
    "    \"\"\"    \n",
    "    if guassian_val % 2 == 1:\n",
    "        img_Gauusian_dst = cv2.GaussianBlur(img_Gauusian, (guassian_val, guassian_val), 0)\n",
    "    else:\n",
    "        guassian_val = guassian_val+1\n",
    "    \"\"\"\n",
    "    img_Gauusian_dst = cv2.GaussianBlur(img_Gauusian, (2*guassian_val+1, 2*guassian_val+1), 0)\n",
    "        \n",
    "    \n",
    "    cv2.imshow(\"image_boxFilter\", img_box_dst)\n",
    "    cv2.imshow(\"image_blur\", img_blur_dst)\n",
    "    cv2.imshow(\"image_GaussianBlur\", img_Gauusian_dst)\n",
    "    \n",
    "    k = cv2.waitKey(1) & 0xFF\n",
    "    if k == 27:\n",
    "        break\n",
    "    \n",
    "\n",
    "\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 几点说明：\n",
    "- 以上所有滤波器的内核值不能为 0，故在程序中设置了当轨迹条值为 0 时，重置为 1。\n",
    "- 高斯滤波器的内核值必须为奇数如：(1, 1)、(3, 3) 等，程序中设置当轨迹条为偶数时，加 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 非线性滤波：中值滤波、双边滤波\n",
    "线性滤波容易构造，并且易于从频率响应的角度来进行分析。\n",
    "\n",
    "许多情况，使用近邻像素的非线性滤波会得到更好的结果。比如在噪声是散粒噪声而不是高斯噪声，即图像偶尔会出现很大值的时候，用高斯滤波器进行图像模糊时，噪声像素不会被消除，而是转化为更为柔和但仍然可见的散粒。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 中值滤波\n",
    "\n",
    "中值滤波（Median filter）是一种典型的非线性滤波技术，基本思想是用像素点邻域灰度值的中值来代替该像素点的灰度值，该方法在去除脉冲噪声、椒盐噪声『椒盐噪声又称脉冲噪声，它随机改变一些像素值，是由图像传感器，传输信道，解码处理等产生的黑白相间的亮暗点噪声。椒盐噪声往往由图像切割引起。』的同时又能保留图像边缘细节，\n",
    "\n",
    "中值滤波是基于排序统计理论的一种能有效抑制噪声的非线性信号处理技术，其基本原理是把数字图像或数字序列中一点的值用该点的一个邻域中各点值的中值代替，让周围的像素值接近的真实值，从而消除孤立的噪声点，对于**斑点噪声（speckle noise）和椒盐噪声（salt-and-pepper noise）**来说尤其有用，因为它不依赖于邻域内那些与典型值差别很大的值。中值滤波器在处理连续图像窗函数时与线性滤波器的工作方式类似，但滤波过程却不再是加权运算。\n",
    "\n",
    "中值滤波在一定的条件下可以克服常见线性滤波器如最小均方滤波、方框滤波器、均值滤波等带来的图像细节模糊，而且对滤除脉冲干扰及图像扫描噪声非常有效，也常用于保护边缘信息, 保存边缘的特性使它在不希望出现边缘模糊的场合也很有用，是非常经典的平滑噪声处理方法。\n",
    "\n",
    "与均值滤波比较：\n",
    "- 优势：消除噪声和保护边缘的效果好\n",
    "- 劣势：消耗的时间是均值滤波的 5 倍左右\n",
    "\n",
    "说明：中值滤波在一定条件下，可以克服线性滤波器（如均值滤波等）所带来的图像细节模糊，而且对滤除脉冲干扰即图像扫描噪声最为有效。在实际运算过程中并不需要图像的统计特性，也给计算带来不少方便。**但是对一些细节多，特别是线、尖顶等细节多的图像不宜采用中值滤波。**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### 程序说明原理\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1fzz2587fxwj20dg08a761.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 疑问？ 图像的边缘中值滤波是如何处理的？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:18:09.829704Z",
     "start_time": "2019-02-26T08:18:09.699775Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([[239, 201, 241, 250, 214],\n",
       "        [255, 119, 255, 202, 219],\n",
       "        [255, 175, 236, 134, 195],\n",
       "        [254, 193, 216, 247, 156],\n",
       "        [219, 247, 248, 212, 168]], dtype=uint8),\n",
       " array([[239, 239, 241, 241, 214],\n",
       "        [239, 239, 202, 219, 214],\n",
       "        [254, 236, 202, 216, 195],\n",
       "        [247, 236, 216, 212, 168],\n",
       "        [219, 247, 247, 212, 168]], dtype=uint8),\n",
       " array([[119, 255, 119, 255, 202, 219, 202],\n",
       "        [201, 239, 201, 241, 250, 214, 250],\n",
       "        [119, 255, 119, 255, 202, 219, 202],\n",
       "        [175, 255, 175, 236, 134, 195, 134],\n",
       "        [193, 254, 193, 216, 247, 156, 247],\n",
       "        [247, 219, 247, 248, 212, 168, 212],\n",
       "        [193, 254, 193, 216, 247, 156, 247]], dtype=uint8))"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 边缘处理\n",
    "img = cv2.imread(\"./sample_img/pic2.png\", 0)\n",
    "img = img[0:5, 0:5]\n",
    "result = cv2.medianBlur(img, 3)\n",
    "img, result, cv2.copyMakeBorder(img, 1, 1, 1, 1, cv2.BORDER_DEFAULT)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### 中值滤波例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:18:12.364251Z",
     "start_time": "2019-02-26T08:18:11.392805Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "img = cv2.imread(\"./sample_img/pic2.png\")\n",
    "\n",
    "median = cv2.medianBlur(img, 3)\n",
    "\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"median\", median)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1fzz1lz6q8uj20ml09bh3j.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 双边滤波\n",
    "双边滤波（Bilateral filter）是一种非线性的滤波方法，是结合**图像的空间邻近度和像素值相似度**的一种折衷处理，同时考虑空域信息和灰度相似性，达到保边去噪的目的。具有简单、非迭代、局部的特点。\n",
    "\n",
    "双边滤波器的好处是可以做边缘保存（edge preserving），一般过去用的维纳滤波或者高斯滤波去降噪，都会较明显地模糊边缘，对于高频细节的保护效果并不明显。双边滤波器顾名思义比高斯滤波多了一个高斯方差 sigma－d ，它是基于空间分布的高斯滤波函数，所以在边缘附近，离的较远的像素不会太多影响到边缘上的像素值，这样就保证了边缘附近像素值的保存。**但是由于保存了过多的高频信息，对于彩色图像里的高频噪声，双边滤波器不能够干净的滤掉，只能够对于低频信息进行较好的滤波。**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:18:15.440488Z",
     "start_time": "2019-02-26T08:18:14.228184Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "img = cv2.imread(\"./sample_img/pic2.png\")\n",
    "\n",
    "bilateralFilter = cv2.bilateralFilter(img, 9, 75, 75)\n",
    "\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"bilateralFilter\", bilateralFilter)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运行结果\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g03w0rao2vj20md099kak.jpg)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 形态学转换 1 - 腐蚀和膨胀\n",
    "学习目标:\n",
    "-  cv2.erode(), cv2.dilate(), cv2.morphologyEx()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 理论\n",
    "形态变换是基于图像形状的一些简单操作。它通常在二进制图像上执行。\n",
    "\n",
    "膨胀与腐蚀实现的功能\n",
    "- 消除噪声\n",
    "- 分割（isolate）出独立的图像元素，在图像中连接（join）相邻的元素\n",
    "- 寻找图像中的明显的极大值区域或极小值区域\n",
    "- 求出图像的梯度"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 腐蚀\n",
    "\n",
    "侵蚀的基本思想就像土壤侵蚀一样，它会侵蚀前景物体的边界（总是试图保持前景为白色）。那它是做什么的？内核在图像中滑动（如在2D卷积中）。只有当内核下的所有像素都是 1 时，原始图像中的像素（ 1 或 0 ）才会被视为 1 ，否则它将被侵蚀（变为零）\n",
    "> 腐蚀就是以内核大小的邻域内取最**小值**作为中心的值\n",
    "\n",
    "\n",
    "`erode(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) -> dst`\n",
    "- src: 源图像\n",
    "- kernel: 内核，通常结合 `getStructuringElement(shape, ksize[, anchor]) -> retval` 一起使用\n",
    "    - shape: 内核的形状，可选参数 \n",
    "        `cv2.MORPH_RECT` `cv2.MORPH_CROSS` `cv2.MORPH_ELLIPSE`\n",
    "    - ksize：内核尺寸\n",
    "    - anchor：锚点位置 默认：(-1, -1) 内核形状的中心。注：十字形的 element 形状唯一依赖于锚点的位置，在其他情形，锚点只影响形态学运算结果的偏移\n",
    "- anchor：锚点位置   \n",
    "- iterations: 迭代使用 erode 的次数，默认为 1\n",
    "- borderType：边界处理参数，默认 cv2.BORDER_DEFAULT\n",
    "- borderValue: 一般不用管它\n",
    "- dst：处理后的图像"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T13:22:15.400534Z",
     "start_time": "2019-03-10T13:22:13.264759Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "def erosion_demo(img):\n",
    "    # kernel = np.ones((5,5),np.uint8) # OpenCV 教程中使用的方法\n",
    "    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 3))\n",
    "    erosion = cv2.erode(img, kernel, iterations = 1)\n",
    "    \n",
    "    cv2.imshow(\"erosion\", erosion)\n",
    "    return erosion\n",
    "\n",
    "img = cv2.imread(\"./sample_img/Morphology_Original_Image.png\", 0)\n",
    "#img = img[0:5, 0:5]\n",
    "erosion = erosion_demo(img)\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g03wwftsr3j206v055q2v.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 膨胀\n",
    "与腐蚀的操作相反。如果内核下的至少一个像素为“1”，则像素元素为“1”。因此它增加了图像中的白色区域或前景对象的大小增加。通常，在去除噪音的情况下，侵蚀之后是扩张。因为，侵蚀会消除白噪声，但它也会缩小我们的物体。所以我们扩大它。由于噪音消失了，它们不会再回来，但我们的物体区域会增加。它也可用于连接对象的破碎部分\n",
    "> 腐蚀就是以内核大小的邻域内取最**大值**作为中心的值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T07:19:37.791214Z",
     "start_time": "2019-03-10T07:19:34.225266Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "\n",
    "def dilation_demo(img):\n",
    "    \"\"\"\n",
    "    膨胀\n",
    "    \"\"\"\n",
    "    # kernel = np.ones((5,5), np.uint8)\n",
    "    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\n",
    "    dilation  = cv2.dilate(img, kernel, iterations = 1)\n",
    "    cv2.imshow(\"dilation\", dilation)\n",
    "    \n",
    "img = cv2.imread(\"./sample_img/Morphology_Original_Image.png\", 0)\n",
    "cv2.imshow(\"img\", img)\n",
    "dilation_demo(img)\n",
    "\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g03xv8hdo9j206r056wee.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 直观例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.406Z"
    }
   },
   "outputs": [],
   "source": [
    "# 创建一个测试图像\n",
    "img = np.zeros((10, 10), dtype=np.uint8)\n",
    "img"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.414Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# 画上一个圆\n",
    "cv2.circle(img, (5, 5), 3, (255, 0, 0), -1)\n",
    "img"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.420Z"
    }
   },
   "outputs": [],
   "source": [
    "# 图像边缘的处理\n",
    "cv2.copyMakeBorder(img, 1, 1, 1, 1, cv2.BORDER_DEFAULT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.433Z"
    }
   },
   "outputs": [],
   "source": [
    "# 结果展示\n",
    "kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n",
    "dilation  = cv2.dilate(img, kernel, iterations = 1)\n",
    "dilation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.441Z"
    }
   },
   "outputs": [],
   "source": [
    "erosion = cv2.erode(img, kernel, iterations = 1)\n",
    "erosion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 形态学转换 2 - 开运算、闭运算、形态学梯度、顶帽、黑帽\n",
    "\n",
    "`morphologyEx(src, op, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) -> dst`\n",
    "- src: 源图像\n",
    "- op: 形态学运算的类型\n",
    "```\n",
    "    - cv2.MORPH_ERODE = 0 腐蚀  \n",
    "    - cv2.MORPH_DILATE = 1膨胀\n",
    "    - cv2.MORPH_OPEN = 2 开运算\n",
    "    - cv2.MORPH_CLOSE = 3 闭运算\n",
    "    - cv2.MORPH_GRADIENT = 4 形态学梯度\n",
    "    - cv2.MORPH_TOPHAT = 5 顶帽\n",
    "    - cv2.MORPH_BLACKHAT = 6 黑帽\n",
    "    - cv2.MORPH_HITMISS = 7  hit or miss\n",
    "```\n",
    "- kernel：内核\n",
    "- dst： 输出"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 开运算\n",
    "先腐蚀后膨胀的过程，对于滤除噪声很有用。\n",
    "\n",
    "开运算可以用来消除小物体，在纤细点分离物体，并且在平滑较大物体的边界的同时不明显改变其面积。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T07:13:23.133623Z",
     "start_time": "2019-03-10T07:13:17.035121Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "def opening_demo(img):\n",
    "    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\n",
    "    opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)\n",
    "    #opening = cv2.morphologyEx(img, 2, kernel) # 同上\n",
    "    cv2.imshow(\"opening\", opening)\n",
    "    \n",
    "    \n",
    "img = cv2.imread(\"./sample_img/Opening_Original_Image.png\", 0)\n",
    "cv2.imshow(\"img\", img)\n",
    "opening_demo(img)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-13T05:50:18.090301Z",
     "start_time": "2019-02-13T05:50:08.640631Z"
    }
   },
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g04r0i2r47j206u053q2t.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 闭运算\n",
    "先膨胀后腐蚀，它在去除前景对象内部的小洞或对象上的小黑点时非常有用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T07:15:50.471905Z",
     "start_time": "2019-03-10T07:15:47.710492Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "def closing_demo(img):\n",
    "    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n",
    "    closing = cv2.morphologyEx(img, 3, kernel)\n",
    "    cv2.imshow(\"closing\", closing)\n",
    "\n",
    "\"\"\"\n",
    "# 创建一个测试图片\n",
    "for num in range(250):\n",
    "    i = np.random.randint(np.where(img==255)[0].shape[0])\n",
    "    img[np.where(img==255)[0][i], np.where(img==255)[1][i]] = 0\n",
    "\"\"\"    \n",
    "\n",
    "img = cv2.imread(\"./sample_img/Closing_Original_Image.png\", 0)                                   \n",
    "cv2.imshow(\"img\", img)\n",
    "closing_demo(img)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g04ssbkqt0j206t04xdfr.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 形态学梯度\n",
    "膨胀图与腐蚀图之差，**保留物体的边缘轮廓**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T01:20:18.665744Z",
     "start_time": "2019-02-26T01:20:16.851786Z"
    }
   },
   "outputs": [],
   "source": [
    "# 例程 1\n",
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "\n",
    "   \n",
    "img = cv2.imread(\"./sample_img/Morphology_Original_Image.png\", 0)\n",
    "kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n",
    "gradient  = cv2.morphologyEx(img, 4, kernel)\n",
    "                                   \n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"gradient \", gradient)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T12:07:26.230734Z",
     "start_time": "2019-03-10T12:07:24.215895Z"
    }
   },
   "outputs": [],
   "source": [
    "# 例程 2\n",
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "def gradient_demo(img):\n",
    "    \"\"\"\n",
    "    img: 灰度图像\n",
    "    \"\"\"\n",
    "    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n",
    "    gradient  = cv2.morphologyEx(img, 4, kernel)\n",
    "    \n",
    "    cv2.imshow(\"gradient \", gradient)\n",
    "    return gradient\n",
    "    \n",
    "    \n",
    "img = cv2.imread(\"./sample_img/Morphology_Original_Image.png\", 0)\n",
    "gradient_demo(img)\n",
    "                                   \n",
    "cv2.imshow(\"img\", img)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g04t6i9cymj206z054dfs.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.496Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/img.jpg\", 0)\n",
    "kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n",
    "gradient = cv2.morphologyEx(img, 4, kernel)\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"gradient \", gradient)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g04to71vnoj20ch054417.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 顶帽（Top Hat）——“礼帽”\n",
    "原图像和开运算的结果之差\n",
    "开运算的效果是放大了裂缝或者局部地亮度的区域，顶帽的效果突出了比原图轮廓周围的区域更明亮的区域，该操作与内核的选择有关。\n",
    "\n",
    "应用场景：分离比邻近点亮的一些斑块，在一幅画像具有大幅的背景而微小物品比较有规律的情况下，可以运用顶帽进行**背景提取。**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T01:21:33.953652Z",
     "start_time": "2019-02-26T01:21:16.393183Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/Morphology_Original_Image.png\")\n",
    "kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9))\n",
    "opening = cv2.morphologyEx(img, 2, kernel)  # 同上\n",
    "tophat = img - opening\n",
    "\n",
    "tophat_2 = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel) # 同上\n",
    "\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"tophat \", tophat)\n",
    "cv2.imshow(\"tophat_2\", tophat_2)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g065ustpqij20ck05140v.jpg)\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g065zgtrjdj206n051wec.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 黑帽\n",
    "闭运算与原图之差\n",
    "\n",
    "运算效果图突出了比原图轮廓周围的区域更暗的区域，与内核的选择有关\n",
    "\n",
    "分离比邻近点暗的斑块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T01:22:10.266019Z",
     "start_time": "2019-02-26T01:21:55.740271Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/cat.jpg\")\n",
    "kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9))\n",
    "closing = cv2.morphologyEx(img, 3, kernel)  \n",
    "blackhat  = closing - img\n",
    "\n",
    "blackhat_2 = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel) # 同上\n",
    "\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"blackhat\", blackhat)\n",
    "cv2.imshow(\"blackhat_2\", blackhat_2)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0670d3lwwj20a4057jre.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 距离变换\n",
    "\n",
    "直观的图，距离变换处理的是二值图像\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0xs4pohs5j20dj055wec.jpg)\n",
    "\n",
    "\n",
    "`distanceTransform(src, distanceType, maskSize[, dst[, dstType]]) -> dst`\n",
    "- src: 8 位单通道（二值）图像\n",
    "- distanceType: 距离计算类型\n",
    "    - DIST_USER \tUser defined distance.\n",
    "    - DIST_L1 \tdistance = |x1-x2| + |y1-y2|\n",
    "    - DIST_L2 \tthe simple euclidean distance\n",
    "    - DIST_C \tdistance = max(|x1-x2|,|y1-y2|)\n",
    "    - DIST_L12 \tL1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1))\n",
    "    - DIST_FAIR \tdistance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998\n",
    "    - DIST_WELSCH \tdistance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846\n",
    "    - DIST_HUBER \tdistance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345\n",
    "    \n",
    "- maskSize: 距离变换的掩模大小\n",
    "    - DIST_MASK_3 \tmask=3\n",
    "    - DIST_MASK_5 \tmask=5\n",
    "    - DIST_MASK_PRECISE \t"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T10:29:20.413338Z",
     "start_time": "2019-03-10T10:29:16.536569Z"
    }
   },
   "outputs": [],
   "source": [
    "#!/ust/bin/python3\n",
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "img = cv2.imread(\"./sample_img/star.jpg\")\n",
    "img = np.zeros((300, 300, 3), dtype=np.uint8)\n",
    "cv2.circle(img, (150, 150), 80, (0, 0, 255), -1)\n",
    "cv2.imshow(\"img\", img)\n",
    "gray = cv2.cvtColor(img, 6)\n",
    "\n",
    "dist = cv2.distanceTransform(src=gray, distanceType=cv2.DIST_L2, maskSize=5)\n",
    "dist1 = cv2.convertScaleAbs(dist)\n",
    "dist2 = cv2.normalize(dist, None, 255, 0, cv2.NORM_MINMAX, cv2.CV_8UC1)\n",
    "\n",
    "cv2.imshow(\"dist\", dist)\n",
    "cv2.imshow(\"dist1\", dist1)\n",
    "cv2.imshow(\"dist2\", dist2)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T10:30:38.952184Z",
     "start_time": "2019-03-10T10:29:40.383856Z"
    }
   },
   "outputs": [],
   "source": [
    "#!/ust/bin/python3\n",
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "def distanceTransform_demo(gray):\n",
    "    \"\"\"\n",
    "    src: 8 位单通道\n",
    "    \"\"\"\n",
    "    dis_transform = cv2.distanceTransform(src=gray,distanceType=cv2.DIST_L2,maskSize=5)\n",
    "    scale = cv2.convertScaleAbs(dis_transform)\n",
    "    normalize = cv2.normalize(dis_transform, None, 255,0, cv2.NORM_MINMAX, cv2.CV_8UC1)\n",
    "    cv2.imshow(\"dis_transform\", dis_transform)\n",
    "    cv2.imshow(\"scale\", scale)\n",
    "    cv2.imshow(\"normalize\", normalize)\n",
    "\n",
    "\n",
    "#img = cv2.imread(\"./sample_img/star.jpg\")\n",
    "img = np.zeros((300, 300, 3), dtype=np.uint8)\n",
    "cv2.circle(img, (150, 150), 80, (0, 0, 255), -1)\n",
    "cv2.imshow(\"img\", img)\n",
    "gray = cv2.cvtColor(img, 6)\n",
    "distanceTransform_demo(gray)\n",
    "\n",
    "\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0xvl01tx9j20xl09awf9.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 结构元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T10:16:25.776695Z",
     "start_time": "2019-03-10T10:16:25.766705Z"
    },
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MORPH_RECT: \n",
      " [[1 1 1 1 1]\n",
      " [1 1 1 1 1]\n",
      " [1 1 1 1 1]\n",
      " [1 1 1 1 1]\n",
      " [1 1 1 1 1]]\n",
      "MORPH_ELLIPSE: \n",
      " [[0 0 1 0 0]\n",
      " [1 1 1 1 1]\n",
      " [1 1 1 1 1]\n",
      " [1 1 1 1 1]\n",
      " [0 0 1 0 0]]\n",
      "MORPH_CROSS: \n",
      " [[0 0 1 0 0]\n",
      " [0 0 1 0 0]\n",
      " [1 1 1 1 1]\n",
      " [0 0 1 0 0]\n",
      " [0 0 1 0 0]]\n"
     ]
    }
   ],
   "source": [
    "print(\"MORPH_RECT: \\n\", cv2.getStructuringElement(cv2.MORPH_RECT,(5,5)))\n",
    "print(\"MORPH_ELLIPSE: \\n\", cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))\n",
    "print(\"MORPH_CROSS: \\n\", cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 更多资料\n",
    "[本节地址] (https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 漫水填充（待续）\n",
    "#### 基本概念\n",
    "##### 定义\n",
    "用特定颜色填充连通区域，通过设置可连通像素的上下限以及连通方式来达到不同的填充效果的方法\n",
    "##### 应用\n",
    "用来标记或者分离图像的一部分，以便对其进行处理或者分析，也可以用来从输入图像获取掩码区域，掩码会加速处理过程，或者只处理掩码部分的像素点，操作的结果总是一个连续的区域。\n",
    "##### 基本思想与算法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 漫水填充实例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:07:49.884543Z",
     "start_time": "2019-02-26T08:07:46.577459Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "img = cv2.imread(\"./sample_img/floodfill.jpg\")\n",
    "mask = np.zeros((img.shape[0]+2, img.shape[1]+2), dtype=np.uint8)\n",
    "ret, dst, mask, rect = cv2.floodFill(img, mask, (155, 255), 255)\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"dst\", dst)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 图像金字塔（主要用于图像分割）\n",
    "学习目标：\n",
    "- 了解 Image Pyramids \n",
    "- cv2.pyrDown(), cv2.pyrUp()\n",
    "\n",
    "#### 基本概念\n",
    "在某些情况下，我们需要处理同一图像的不同分辨率的图像。例如，在搜索图像中的某些内容时，如脸部，我们不确定对象在图像中的大小。在这种情况下，我们需要创建一组具有不同分辨率的图像，并在所有图像中搜索对象。这些具有不同分辨率的图像被称为图像金字塔（因为它们被保存在堆叠中，底部最大图像，顶部最小图像看起来像金字塔）。\n",
    "\n",
    "cv2.pyrDown(), cv2.pyrUp() 函数的功能和缩小，放大图片差不多，与 cv2.resize() 功能差不多，但它们分属不同的模块。\n",
    "\n",
    "**注意： pyrDown、pyrUp 两者不是一个互逆过程**\n",
    "\n",
    "#### 类型\n",
    "- 高斯金字塔：用来向下采样，主要的图像金字塔\n",
    "- 拉普拉斯金字塔：用来从金字塔低层图像重建上层未采样图像，在图像处理中即预测残差，可以对图像最大程度的进行还原，配合高斯金字塔一起使用。\n",
    "- 区别：高斯金字塔用来向下降采样图像，拉普拉斯金字塔则用来从底层图像中向上采样，重建一个图像。\n",
    "\n",
    "**向上采样——放大， 向下采样——缩小**\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T02:41:46.823725Z",
     "start_time": "2019-02-26T02:40:42.744294Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "img = cv2.imread(\"messi5.jpg\")\n",
    "down = cv2.pyrDown(img)\n",
    "up = cv2.pyrUp(down)\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"down\", down)\n",
    "cv2.imshow(\"up\", up)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "先对图像进行缩小，再对缩小后的图像进行放大，放大后的图像变得模糊了\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0jmlpm1t3j211p0agauu.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T01:47:45.886247Z",
     "start_time": "2019-02-26T01:47:45.878219Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((342, 548, 3), (171, 274, 3), (684, 1096, 3))"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "img.shape, down.shape, up.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0jl3x7x3uj21170jvb29.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 图像金字塔进行图像混合（苹果和橙子混合）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 基本原理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![第一步](https://ws1.sinaimg.cn/large/acbcfa39gy1g0jnyo8h9xj20d70ciq3u.jpg)\n",
    "![第二步](https://ws1.sinaimg.cn/large/acbcfa39gy1g0jtlf1rw0j20cg0bidgu.jpg)\n",
    "![第三步](https://ws1.sinaimg.cn/large/acbcfa39gy1g0jtm2svkbj20cg0fi0uc.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 分步例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:05:13.114656Z",
     "start_time": "2019-02-26T08:04:53.813445Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import sys\n",
    "\n",
    "A = cv2.imread('./sample_img/apple.jpg')\n",
    "B = cv2.imread('./sample_img/orange.jpg')\n",
    "\n",
    "# generate Gaussian pyramid for A\n",
    "# 生成高斯金字塔，即一步一步缩小\n",
    "G = A.copy()\n",
    "gpA = [G]\n",
    "for i in range(6):\n",
    "    G = cv2.pyrDown(G)\n",
    "    gpA.append(G)\n",
    "\n",
    "# generate Gaussian pyramid for B\n",
    "G = B.copy()\n",
    "gpB = [G]\n",
    "for i in range(6):\n",
    "    G = cv2.pyrDown(G)\n",
    "    gpB.append(G)\n",
    "\n",
    "# 生成拉普拉斯金字塔，即在高斯金字塔变换后进行多次 pyrUp 函数变换    \n",
    "# generate Laplacian Pyramid for A\n",
    "lpA = [gpA[5]]\n",
    "for i in range(5, 0, -1):\n",
    "    GE = cv2.pyrUp(gpA[i])\n",
    "    L = cv2.subtract(gpA[i-1], GE)\n",
    "    lpA.append(L)\n",
    "\n",
    "# generate Laplacian Pyramid for B\n",
    "lpB = [gpB[5]]\n",
    "for i in range(5, 0, -1):\n",
    "    GE = cv2.pyrUp(gpB[i])\n",
    "    L = cv2.subtract(gpB[i-1], GE)\n",
    "    lpB.append(L)\n",
    "\n",
    "# Now add left and right halves of images in each level\n",
    "LS = []\n",
    "for la, lb in zip(lpA, lpB):\n",
    "    rows, cols, dpt = la.shape\n",
    "    ls = np.hstack((la[:, 0:cols//2], lb[:, cols//2:]))\n",
    "    LS.append(ls)\n",
    "\n",
    "# now reconstruct\n",
    "ls_ = LS[0]\n",
    "for i in range(1, 6):\n",
    "    ls_ = cv2.pyrUp(ls_)\n",
    "    ls_ = cv2.add(ls_, LS[i])\n",
    "\n",
    "# 直接进行连接的效果    \n",
    "# image with direct connecting each half\n",
    "real = np.hstack((A[:, :cols//2], B[:, cols//2:]))\n",
    "\n",
    "cv2.imshow('Pyramid_blending2.jpg', ls_)\n",
    "cv2.imshow('Direct_blending.jpg', real)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0jvy5o9a8j20hy09vakp.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 图像金字塔函数封装"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:05:25.850249Z",
     "start_time": "2019-02-26T08:05:25.832222Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "def img_pyramids(src1, src2, num):\n",
    "    \"\"\"\n",
    "    src1: 图像 1\n",
    "    src2: 图像 2\n",
    "    num: 金字塔层数\n",
    "    \"\"\"\n",
    "    # 判断两张图片的大小是否匹配\n",
    "    if src1.shape == src2.shape:    \n",
    "        # 找到 src1 和 src2 的高斯金字塔\n",
    "        src1_G = src1.copy()  # 中间变量保存每次的变换值\n",
    "        src1_gp = [src1_G]  # src1 的图像高斯金字塔\n",
    "        src2_G = src2.copy()  # 中间变量保存每次的变换值\n",
    "        src2_gp = [src2_G]  # src2 的图像高斯金字塔\n",
    "        for i in range(num):\n",
    "            src1_gp.append(cv2.pyrDown(src1_gp[i]))\n",
    "            src2_gp.append(cv2.pyrDown(src2_gp[i]))\n",
    "\n",
    "        # 从高斯金字塔找到拉普拉斯金字塔\n",
    "        src1_lp = [src1_gp[num-1]]  # 拉普拉斯金字塔保存，最后一个高斯金字塔就是第一个拉普拉斯金字塔\n",
    "        src2_lp = [src2_gp[num-1]] \n",
    "        for i in range(num-1, 0, -1):\n",
    "            src1_lp.append(cv2.subtract(src1_gp[i-1], cv2.pyrUp(src1_gp[i])))\n",
    "            src2_lp.append(cv2.subtract(src2_gp[i-1], cv2.pyrUp(src2_gp[i])))\n",
    "\n",
    "        # 拉普拉斯各层金字塔进行合并\n",
    "        LS = []\n",
    "        for L1, L2 in zip(src1_lp, src2_lp):\n",
    "            rows, clos, ch = L1.shape\n",
    "            LS.append(np.hstack((L1[:, 0:clos//2], L2[:, clos//2:])))\n",
    "        \n",
    "        ls = LS[0]\n",
    "        for i in range(1, num):\n",
    "            ls = cv2.pyrUp(ls)\n",
    "            ls = cv2.add(ls, LS[i])\n",
    "        return ls\n",
    "    else:\n",
    "        return -1\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-26T08:05:35.293840Z",
     "start_time": "2019-02-26T08:05:26.632763Z"
    }
   },
   "outputs": [],
   "source": [
    "A = cv2.imread('./sample_img/apple.jpg')\n",
    "B = cv2.imread('./sample_img/orange.jpg')\n",
    "\n",
    "\n",
    "def nothing(x):\n",
    "    pass\n",
    "\n",
    "cv2.namedWindow(\"result\")\n",
    "cv2.createTrackbar(\"num\", \"result\", 0, 7, nothing) # \n",
    "\n",
    "while(1):\n",
    "    num = cv2.getTrackbarPos(\"num\", \"result\")\n",
    "    cv2.imshow(\"result\", img_pyramids(A, B, num)) # num 不能太大，太大的话程序会报错，应该是图像太小后无法求高斯金字塔\n",
    "\n",
    "    k = cv2.waitKey(1) & 0xff\n",
    "    if k == 27:\n",
    "        break\n",
    "        \n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0jvykhqk9j209d0badky.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 更多资料\n",
    "[Image Blending] (http://pages.cs.wisc.edu/~csverma/CS766_09/ImageMosaic/imagemosaic.html)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 边缘检测"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 边缘检测\n",
    "边缘检测的一般步骤：\n",
    "1. 滤波：边缘检测算法主要是基于图像强度的一阶和二阶导数，但导数通常对噪声很敏感，因此需要采用滤波来改善边缘检测器的性能。常用的滤波方法有高斯滤波。\n",
    "2. 增强：增强边缘的基础是确定图像各点邻域强度的变化值。增强算法可以将图像灰度点邻近强度值有显著变化的点凸显出来。通过计算梯度幅值来确定。\n",
    "3. 检测：通过增强的图像，往往邻域中有很多点的梯度值比较大，在特定应用中，这些点并不是要找的边缘点，所以应该采用某种方法来对这些点进行取舍，常用的方法是通过阈值化方法来检测。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "学习目标\n",
    "- 查找图像梯度，边缘等\n",
    "-  cv2.Sobel(), cv2.Scharr(), cv2.Laplacian()\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "OpenCV 有三种类型的梯度滤波器或高通滤波器 Sobel, Scharr 和 Laplacian.\n",
    "\n",
    "- Sobel 算子\n",
    "用于边缘检测的离散微分算子。结合律高斯平滑和微分求导，用来计算图像灰度函数的近似梯度，在图像的任何一点使用此算子，都会产生对应的梯度矢量或者其法向量。\n",
    "- Sobel 算子的计算过程\n",
    "    - 水平变化，设图像为 I\n",
    "    ![](https://docs.opencv.org/2.4/_images/math/42c8a258fd1418ea1caf81d3c5e2374b50b3abd2.png)\n",
    "    - 垂直变化\n",
    "    ![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0ihv0qtu7j205d01vwe9.jpg)\n",
    "    - 对图像的每个点进行处理，来得到导数的近似值\n",
    "    ![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0ihvu08rij203d00y0rh.jpg)\n",
    "    - 有时也有下面的结果来代替\n",
    "    ![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0ihwnxqyuj203900j0lp.jpg)\n",
    "    \n",
    "Sobel 算子可以计算**一阶， 二阶， 三阶或者混合图像差分**\n",
    "\n",
    "\n",
    "\n",
    "`Sobel(src, ddepth, dx, dy[, dst[, ksize[, scale[, delta[, borderType]]]]]) -> dst`\n",
    "- src: 原图像\n",
    "- ddepth: 输出图像的深度\n",
    "    - src.depth() = CV_8U, ddepth = -1/CV_16S/CV_32F/CV_64F\n",
    "    - src.depth() = CV_16U/CV_16S, ddepth = -1/CV_32F/CV_64F\n",
    "    - src.depth() = CV_32F, ddepth = -1/CV_32F/CV_64F\n",
    "    - src.depth() = CV_64F, ddepth = -1/CV_64F\n",
    "- dx: x 方向的差分阶数\n",
    "- dy: y 方向的差分阶数\n",
    "- ksize: 内核大小，必须是奇数，默认为 3 \n",
    "- scale: 计算导数时可选的缩放因子，默认为 1 表示没有进行缩放\n",
    "- delta: 表示结果存入目标图, dst 参数\n",
    "- borderType: 边界处理参数\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "当内核为 3 时，Sobel 内核可能产生比较明显的误差，为此， OpenCV 提供了 **Scharr** 函数，该函数**只作用与大小为 3 的内核**，与 Sobel 函数一样快，但是**精度更高**。\n",
    "\n",
    "Sobel 算子结合了高斯平滑和分化，因此结果具有抗噪性，大多数，使用 Sobel 函数时 【dx=1, dy=0, ksize=3】 来计算图像 X 方向的导数，dx=0, dy=1, ksize=3】 来计算 Y 方向的导数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.760Z"
    }
   },
   "outputs": [],
   "source": [
    "%matplotlib notebook\n",
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "img = cv2.imread(\"./sample_img/dave.png\", 0)\n",
    "# laplacian = cv2.Laplacian(img, cv2.CV_64F)\n",
    "sobelx = cv2.Sobel(img, cv2.CV_16S, 1, 0, ksize=3)\n",
    "sobely = cv2.Sobel(img, cv2.CV_16S, 0, 1, ksize=3)\n",
    "sobelx_abs = cv2.convertScaleAbs(sobelx) # 取绝对值\n",
    "sobely_abs = cv2.convertScaleAbs(sobely)\n",
    "\n",
    "dst = cv2.addWeighted(sobelx_abs, 0.5, sobely_abs, 0.5, 0) # 将 x, y 两个梯度的图像结合起来\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "plt.subplot(2, 3, 1), plt.imshow(img, cmap='gray')\n",
    "plt.title('Original'), plt.xticks([]), plt.yticks([])\n",
    "plt.subplot(2, 3, 2), plt.imshow(laplacian, cmap='gray')\n",
    "plt.title('Laplacian'), plt.xticks([]), plt.yticks([])\n",
    "plt.subplot(2, 3, 3), plt.imshow(sobelx, cmap='gray')\n",
    "plt.title('Sobel X'), plt.xticks([]), plt.yticks([])\n",
    "plt.subplot(2, 3, 4), plt.imshow(sobely, cmap='gray')\n",
    "plt.title('Sobel Y'), plt.xticks([]), plt.yticks([])\n",
    "plt.subplot(2, 3, 5), plt.imshow(sobelx_abs, cmap='gray')\n",
    "plt.title('sobelx_abs'), plt.xticks([]), plt.yticks([])\n",
    "plt.subplot(2, 3, 6), plt.imshow(sobely_abs, cmap='gray')\n",
    "plt.title('sobely_abs'), plt.xticks([]), plt.yticks([])\n",
    "plt.show()\n",
    "\"\"\"\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"soblex\", sobelx)\n",
    "cv2.imshow(\"sobely\", sobely)\n",
    "cv2.imshow(\"sobelx_abs\", sobelx_abs)\n",
    "cv2.imshow(\"sobely_abs\", sobely_abs)\n",
    "cv2.imshow(\"Dst\", dst)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0im9wyazhj20vb0gmk7h.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 边缘检测函数封装"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.768Z"
    }
   },
   "outputs": [],
   "source": [
    "def sobel_edge(src, ddepth, ksize):\n",
    "    \"\"\"\n",
    "    src: 灰度图像\n",
    "    ddepth:  cv2.CV_64F\n",
    "    ksize: eg. 3、5\n",
    "    \"\"\"\n",
    "    sobelx = cv2.Sobel(src, ddepth, 1, 0, ksize)\n",
    "    sobely = cv2.Sobel(src, ddepth, 0, 1, ksize)\n",
    "    sobelx_abs = cv2.convertScaleAbs(sobelx)\n",
    "    sobely_abs = cv2.convertScaleAbs(sobely)\n",
    "\n",
    "    dst = cv2.addWeighted(sobelx_abs, 0.5, sobely_abs, 0.5, 0)\n",
    "    return dst"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.779Z"
    }
   },
   "outputs": [],
   "source": [
    "def scharr_edge(src, ddepth):\n",
    "    scharrx = cv2.Scharr(src, ddepth, 1, 0, 3)\n",
    "    scharry = cv2.Scharr(src, ddepth, 0, 1, 3)\n",
    "    scharrx_abs = cv2.convertScaleAbs(scharrx)\n",
    "    scharry_abs = cv2.convertScaleAbs(scharry)\n",
    "    \n",
    "    dst = cv2.addWeighted(scharrx_abs, 0.5, scharry_abs, 0.5, 0)\n",
    "    return dst"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.786Z"
    }
   },
   "outputs": [],
   "source": [
    "img = cv2.imread(\"./sample_img/dave.png\", 0)\n",
    "sobel_opt = sobel_edge(img, cv2.CV_64F, 3)\n",
    "scharr_opt = scharr_edge(img, cv2.CV_64F)\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"sobel_opt\", sobel_opt)\n",
    "cv2.imshow(\"scharr_opt\", scharr_opt)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0inuxz5jxj211o0ggqpw.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### OpenCV 数据类型问题（ cv2.CV_8U  cv2.CV_32F 等）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在上一个示例中，输出数据类型是 cv2.CV_8U 或 np.uint8 。但是有一个小问题。黑到白的过渡被认为是正斜率(它有一个正值)，而白到黑的过渡被认为是负斜率(它有一个负值)。当你把数据转换成 np.uint8 ，所有负斜率都为 0 。简单地说，有一边缘不是很清晰。\n",
    "\n",
    "解决方法：\n",
    "如果希望同时检测这两条边，更好的选择是将输出数据类型保留为某些更高的形式，比如 cv2.CV_16S cv2.CV_64F 等，取其绝对值，然后转换回 cv2.CV_8U 。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2019-02-25T07:41:02.794Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "# 创建一个示例图像\n",
    "img = np.zeros((200, 200, 3), dtype=np.uint8)\n",
    "cv2.rectangle(img, (50, 50), (150, 150), (255, 255, 255), -1)\n",
    "\n",
    "# Output dtype = cv2.CV_8U\n",
    "sobelx8u = cv2.Sobel(img, cv2.CV_8U, 1, 0, ksize=5)\n",
    "\n",
    "# Output dtype = cv2.CV_64F. Then take its absolute and convert to cv2.CV_8U\n",
    "sobelx64f = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)\n",
    "abs_sobel64f = np.absolute(sobelx64f)\n",
    "sobel_8u = np.uint8(abs_sobel64f)\n",
    "\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"sobelx8u\", sobelx8u)\n",
    "cv2.imshow(\"sobel_8u\", sobel_8u)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-25T05:27:32.786557Z",
     "start_time": "2019-02-25T05:27:32.776563Z"
    }
   },
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0im0v8wmdj20h106h3yi.jpg)\n",
    "\n",
    "sobelx8u: 图像是经过 cv2.CV_8U 变换后的图像，一边的边缘消失了\n",
    "\n",
    "sobel_8u: 图像经过 cv2.CV_64F 变换后再取绝对值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 参考资料"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[本节原文] (https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_gradients/py_gradients.html)\n",
    "\n",
    "[Image Filtering] (https://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html?highlight=sobel#cv.Sobel)\n",
    "\n",
    "[OpenCV Constant Field Values] (https://docs.opencv.org/java/2.4.9/constant-values.html#org.opencv.core.CvType.CV_16S)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Canny 边缘检测\n",
    "学习目标：\n",
    "- Canny 边缘检测的概念\n",
    "- cv2.Canny()\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 基本概念\n",
    "最优边缘检测的三个评价标准\n",
    "- 低错误率：标识出尽可能多的实际边缘，同时减少噪声产生的误报。\n",
    "- 高定位性：标识出的边缘要与图像中的实际边缘尽可能近。\n",
    "- 最小响应：图像中的边缘只能标识一次，并且尽可能存在的图像噪声不应该标识为边缘。\n",
    "\n",
    "\n",
    "`Canny(image, threshold1, threshold2[, edges[, apertureSize[, L2gradient]]]) -> edges`\n",
    "- image: 源图像\n",
    "- threshold1: 第一个滞后性阈值\n",
    "- threshold2: 第二个滞后性阈值\n",
    "- apertureSize: 表示应用 Sobel 算子的孔径大小\n",
    "- L2gradient: 计算图像梯度幅值的标识，布尔型，默认 False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 初级用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T11:55:40.996881Z",
     "start_time": "2019-03-10T11:55:35.691932Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "# 初级用法，直接调用函数\n",
    "img = cv2.imread(\"./sample_img/messi5.jpg\", 0)\n",
    "canny_img = cv2.Canny(img, 100, 200)\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"canny_img\", canny_img)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0iqdqh5ptj20uo0agn2o.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 高级用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-25T08:06:35.807186Z",
     "start_time": "2019-02-25T08:06:11.921008Z"
    }
   },
   "outputs": [],
   "source": [
    "# 高阶用法，灰度转化，降噪，使用 Canny ，得到的边缘作为掩码拷贝到原图上\n",
    "img = cv2.imread(\"./sample_img/img.jpg\")\n",
    "img1 = img.copy()\n",
    "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "blur_img = cv2.blur(gray, (5, 5))\n",
    "canny_img = cv2.Canny(blur_img, 3, 9)\n",
    "dst = cv2.bitwise_and(img1, img1, mask=canny_img)\n",
    "\n",
    "cv2.imshow(\"img\", img1)\n",
    "cv2.imshow(\"blur_img\", blur_img)\n",
    "cv2.imshow(\"canny_img\", canny_img)\n",
    "cv2.imshow(\"dst\", dst)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0iqdb3bacj20p005an0b.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-25T07:29:20.479833Z",
     "start_time": "2019-02-25T07:29:20.474840Z"
    }
   },
   "source": [
    "##### 轨迹条调节阈值例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T11:59:35.447089Z",
     "start_time": "2019-03-10T11:58:21.223761Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "def nothing(x):\n",
    "    pass\n",
    "\n",
    "\n",
    "cv2.namedWindow(\"dst\")\n",
    "cv2.createTrackbar(\"low\", \"dst\", 0, 255, nothing)\n",
    "cv2.createTrackbar(\"high\", \"dst\", 0, 255, nothing)\n",
    "\n",
    "while(1):\n",
    "    #img = cv2.imread(\"./sample_img/messi5.jpg\")\n",
    "    img = cv2.imread(\"./sample_img/cat.jpg\")\n",
    "    low = cv2.getTrackbarPos(\"low\", \"dst\")\n",
    "    high = cv2.getTrackbarPos(\"high\", \"dst\")\n",
    "    img1 = img.copy()\n",
    "\n",
    "    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "    blur_img = cv2.GaussianBlur(gray, (5, 5), 0)\n",
    "    canny_img = cv2.Canny(blur_img, low, high)\n",
    "    dst = cv2.bitwise_and(img1, img1, mask=canny_img)\n",
    "\n",
    "    cv2.imshow(\"img1\", img1)\n",
    "    cv2.imshow(\"dst\", dst)\n",
    "\n",
    "    k = cv2.waitKey(1) & 0xff\n",
    "    if k == 27:\n",
    "        break\n",
    "\n",
    "\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-25T07:42:50.354615Z",
     "start_time": "2019-02-25T07:42:50.348621Z"
    }
   },
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0iqcncwz7j20uu0crwr8.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 拉普拉斯 Laplacian\n",
    "`Laplacian(src, ddepth[, dst[, ksize[, scale[, delta[, borderType]]]]]) -> dst`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-10T11:57:32.085014Z",
     "start_time": "2019-03-10T11:57:28.334190Z"
    }
   },
   "outputs": [],
   "source": [
    "img = cv2.imread(\"./sample_img/Laplacian.jpg\")\n",
    "gaussian_blur = cv2.GaussianBlur(img, (3, 3), 0)\n",
    "gray = cv2.cvtColor(gaussian_blur, cv2.COLOR_BGR2GRAY)\n",
    "laplacian = cv2.Laplacian(gray, cv2.CV_64F)\n",
    "dst = cv2.convertScaleAbs(laplacian)\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"dst\", dst)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0ir8aas0qj20sh0lc4qp.jpg)"
   ]
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "256.5px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "position": {
    "height": "452px",
    "left": "358px",
    "right": "20px",
    "top": "120px",
    "width": "303px"
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
